from django.contrib.auth.models import AbstractUser
from django.db import models
from apps.common.models import TimestampMixin


class User(AbstractUser, TimestampMixin):
    """用户模型 - 扩展Django默认用户模型"""
    
    # 基础信息
    email = models.EmailField(unique=True, verbose_name="邮箱")
    real_name = models.CharField(max_length=50, blank=True, verbose_name="真实姓名")
    phone = models.CharField(max_length=20, blank=True, verbose_name="手机号")
    
    # 状态管理
    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '未激活'),
        ('suspended', '暂停'),
    ]
    status = models.CharField(
        max_length=20, 
        choices=STATUS_CHOICES, 
        default='active', 
        verbose_name="状态"
    )
    
    # 部门信息（预留字段）
    department_id = models.IntegerField(null=True, blank=True, verbose_name="部门ID")
    
    # 登录信息
    last_login_at = models.DateTimeField(null=True, blank=True, verbose_name="最后登录时间")
    
    # 使用email作为登录字段
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    
    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['email']),
            models.Index(fields=['username']),
            models.Index(fields=['status']),
        ]
    
    def __str__(self):
        return f"{self.username} ({self.email})"
    
    def get_full_name(self):
        """获取完整姓名"""
        return self.real_name or self.username
    
    def can_login(self):
        """检查是否可以登录"""
        return self.status == 'active' and self.is_active
    
    def can_edit_profile(self, user):
        """检查是否可以编辑个人资料"""
        return user == self or user.is_staff
    
    def can_delete(self, user):
        """检查是否可以删除用户"""
        return user.is_staff and user != self
